import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, ScrollView, Image, Alert, Keyboard } from 'react-native';
import React, { useState } from 'react';
import { Stack } from 'expo-router';
import { useTheme } from '../context/ThemeContext';
import { searchUserByStudentId, sendFriendRequest } from '../services/chatService';
import { MaterialCommunityIcons } from '@expo/vector-icons';

export default function AddFriendScreen() {
  const { isDarkMode } = useTheme();
  const [searchText, setSearchText] = useState('');
  const [searching, setSearching] = useState(false);
  const [sending, setSending] = useState(false);
  const [searchResult, setSearchResult] = useState<any>(null);
  const [message, setMessage] = useState('');
  
  // 搜索用户
  const handleSearch = async () => {
    if (!searchText.trim()) {
      Alert.alert('提示', '请输入学号');
      return;
    }
    
    Keyboard.dismiss();
    
    try {
      setSearching(true);
      setSearchResult(null);
      
      // 在实际应用中，这里应该调用API
      // const result = await searchUserByStudentId(searchText.trim());
      
      // 模拟搜索结果
      setTimeout(() => {
        if (searchText.trim() === '20220101') {
          const mockUser = {
            id: 2,
            studentId: '20220101',
            userName: '李四',
            userAvatar: 'https://randomuser.me/api/portraits/men/2.jpg',
            userProfile: '软件工程专业学生',
            college: '计算机学院',
            major: '软件工程',
            grade: '2022级'
          };
          setSearchResult(mockUser);
        } else {
          setSearchResult(null);
          Alert.alert('提示', '未找到该学号的用户');
        }
        setSearching(false);
      }, 1000);
      
    } catch (error) {
      console.error('搜索用户失败:', error);
      Alert.alert('错误', '搜索用户失败，请重试');
      setSearching(false);
    }
  };
  
  // 发送好友请求
  const handleSendRequest = async () => {
    if (!searchResult) return;
    
    try {
      setSending(true);
      
      // 在实际应用中，这里应该调用API
      // await sendFriendRequest(searchResult.id, message);
      
      // 模拟发送请求
      setTimeout(() => {
        setSending(false);
        Alert.alert('成功', '好友请求已发送');
        setSearchResult(null);
        setSearchText('');
        setMessage('');
      }, 1000);
      
    } catch (error) {
      console.error('发送好友请求失败:', error);
      Alert.alert('错误', '发送好友请求失败，请重试');
      setSending(false);
    }
  };
  
  return (
    <>
      <Stack.Screen options={{ 
        title: '添加好友',
        headerStyle: {
          backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF',
        },
        headerTintColor: isDarkMode ? '#FFFFFF' : '#333333',
      }} />
      
      <ScrollView 
        style={[
          styles.container,
          { backgroundColor: isDarkMode ? '#121212' : '#F5F5F5' }
        ]}
        contentContainerStyle={styles.contentContainer}
        keyboardShouldPersistTaps="handled"
      >
        {/* 搜索框 */}
        <View style={styles.searchSection}>
          <Text style={[
            styles.sectionTitle,
            { color: isDarkMode ? '#FFFFFF' : '#000000' }
          ]}>
            通过学号搜索用户
          </Text>
          
          <View style={styles.searchInputContainer}>
            <TextInput
              style={[
                styles.searchInput,
                { 
                  backgroundColor: isDarkMode ? '#2A2A2A' : '#FFFFFF',
                  color: isDarkMode ? '#FFFFFF' : '#000000',
                  borderColor: isDarkMode ? '#555555' : '#DDDDDD'
                }
              ]}
              placeholder="输入学号"
              placeholderTextColor={isDarkMode ? '#999999' : '#999999'}
              value={searchText}
              onChangeText={setSearchText}
              keyboardType="numeric"
              maxLength={8}
            />
            
            <TouchableOpacity
              style={[
                styles.searchButton,
                { backgroundColor: isDarkMode ? '#3B82F6' : '#2563EB' }
              ]}
              onPress={handleSearch}
              disabled={searching || !searchText.trim()}
            >
              {searching ? (
                <ActivityIndicator size="small" color="#FFFFFF" />
              ) : (
                <Text style={styles.searchButtonText}>搜索</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 搜索结果 */}
        {searchResult && (
          <View style={[
            styles.resultSection,
            { 
              backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF',
              borderColor: isDarkMode ? '#333333' : '#EEEEEE'
            }
          ]}>
            <View style={styles.userInfoContainer}>
              <Image 
                source={{ uri: searchResult.userAvatar }} 
                style={styles.avatar}
              />
              
              <View style={styles.userInfo}>
                <Text style={[
                  styles.userName,
                  { color: isDarkMode ? '#FFFFFF' : '#000000' }
                ]}>
                  {searchResult.userName}
                </Text>
                
                <Text style={[
                  styles.userDetails,
                  { color: isDarkMode ? '#BBBBBB' : '#666666' }
                ]}>
                  学号: {searchResult.studentId}
                </Text>
                
                <Text style={[
                  styles.userDetails,
                  { color: isDarkMode ? '#BBBBBB' : '#666666' }
                ]}>
                  {searchResult.college} / {searchResult.major} / {searchResult.grade}
                </Text>
                
                <Text style={[
                  styles.userProfile,
                  { color: isDarkMode ? '#BBBBBB' : '#666666' }
                ]}>
                  {searchResult.userProfile || '暂无个人介绍'}
                </Text>
              </View>
            </View>
            
            <View style={styles.requestSection}>
              <Text style={[
                styles.requestLabel,
                { color: isDarkMode ? '#FFFFFF' : '#000000' }
              ]}>
                验证信息：
              </Text>
              
              <TextInput
                style={[
                  styles.requestInput,
                  {
                    backgroundColor: isDarkMode ? '#2A2A2A' : '#F5F5F5',
                    color: isDarkMode ? '#FFFFFF' : '#000000',
                    borderColor: isDarkMode ? '#555555' : '#DDDDDD'
                  }
                ]}
                placeholder="请输入验证信息"
                placeholderTextColor={isDarkMode ? '#999999' : '#999999'}
                value={message}
                onChangeText={setMessage}
                multiline
              />
              
              <TouchableOpacity
                style={[
                  styles.sendButton,
                  { backgroundColor: isDarkMode ? '#3B82F6' : '#2563EB' }
                ]}
                onPress={handleSendRequest}
                disabled={sending}
              >
                {sending ? (
                  <ActivityIndicator size="small" color="#FFFFFF" />
                ) : (
                  <Text style={styles.sendButtonText}>发送好友请求</Text>
                )}
              </TouchableOpacity>
            </View>
          </View>
        )}
        
        {/* 其他添加方式 */}
        <View style={styles.otherMethodsSection}>
          <Text style={[
            styles.sectionTitle,
            { color: isDarkMode ? '#FFFFFF' : '#000000' }
          ]}>
            其他添加方式
          </Text>
          
          <TouchableOpacity 
            style={[
              styles.methodItem,
              { 
                backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF',
                borderColor: isDarkMode ? '#333333' : '#EEEEEE'
              }
            ]}
            onPress={() => Alert.alert('提示', '扫描二维码功能暂未实现')}
          >
            <MaterialCommunityIcons 
              name="qrcode-scan" 
              size={24} 
              color={isDarkMode ? '#3B82F6' : '#2563EB'} 
            />
            <Text style={[
              styles.methodText,
              { color: isDarkMode ? '#FFFFFF' : '#000000' }
            ]}>
              扫描二维码添加
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  contentContainer: {
    padding: 16,
  },
  searchSection: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  searchInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchInput: {
    flex: 1,
    height: 40,
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 10,
  },
  searchButton: {
    marginLeft: 10,
    height: 40,
    paddingHorizontal: 15,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  searchButtonText: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  resultSection: {
    marginBottom: 20,
    borderRadius: 8,
    padding: 16,
    borderWidth: 1,
  },
  userInfoContainer: {
    flexDirection: 'row',
    marginBottom: 15,
  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
  },
  userInfo: {
    flex: 1,
    marginLeft: 15,
    justifyContent: 'center',
  },
  userName: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  userDetails: {
    fontSize: 14,
    marginBottom: 3,
  },
  userProfile: {
    fontSize: 14,
    marginTop: 5,
  },
  requestSection: {
    marginTop: 10,
  },
  requestLabel: {
    fontSize: 16,
    marginBottom: 10,
  },
  requestInput: {
    borderWidth: 1,
    borderRadius: 8,
    padding: 10,
    minHeight: 80,
    textAlignVertical: 'top',
  },
  sendButton: {
    marginTop: 15,
    height: 40,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  sendButtonText: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  otherMethodsSection: {
    marginBottom: 20,
  },
  methodItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderRadius: 8,
    borderWidth: 1,
  },
  methodText: {
    fontSize: 16,
    marginLeft: 15,
  }
}); 